import React from 'react'
import { Input, Upload, Button, Modal, message } from 'antd'
import ossHttp from '@/utils/oss'
import { getOssFileKey } from '@/utils/methods'
import classNames from 'classnames'
import './uploader.scss'

interface IProps {
  value?: any
  fileList?: any
  accept?: string
  ossDelete?: boolean
  ossPath?: string
  extra?: string
  form?: any
  updateFiles?: any
}
interface IState {
  fileList: any
  previewVisible: boolean
  previewImage: string
  updateFiles?: any
  uploadLoading?: boolean
  uploadText?: string
}
export default class UdUploader extends React.Component<IProps, IState> {
  private ossPath = 'settled-review/annex'
  private accept = 'image/jpg,image/jpeg,image/png,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,application/msword'
  private updateFiles = this.props.updateFiles
  constructor(props: IProps, state: IState) {
    super(props)
    this.ossPath = this.props.ossPath || this.ossPath
    this.accept = this.props.accept || this.accept
    this.accept = this.accept.replace(/\s+/g, '')
    this.state = {
      fileList: this.props.value || [],
      previewVisible: false,
      previewImage: '',
      uploadLoading: false,
      uploadText: '上传',
    }
  }
  componentDidMount() {}
  // 附件上传
  private handleUpload = file => {
    const allowAccept = this.accept.split(',')
    const isAllow = allowAccept.includes(file.type)
    if (!isAllow) {
      // console.warn('File accept type:', this.accept)
      message.warning('不支持此类文件' + file.type)
      return false
    }
    const fileItem = {
      uid: file.uid,
      name: file.name,
      status: 'uploading',
      url: '',
    }
    this.setState({
      uploadLoading: true,
      uploadText: '上传中',
    })
    ossHttp
      .put(this.ossPath, file)
      .then(res => {
        fileItem.url = res.url
        fileItem.status = 'done'
        let fileList = []
        this.setState(
          preState => {
            fileList = [...preState.fileList, fileItem]
            return { fileList }
          },
          () => {
            if (this.updateFiles) {
              this.updateFiles(fileList)
            } else {
              this.props.form && this.props.form.setFieldsValue({ quotaApplyDetailFileRespVoList: fileList })
            }
          }
        )
      })
      .finally(() => {
        this.setState({
          uploadLoading: false,
          uploadText: '上传',
        })
      })
    return false
  }

  // 附件删除
  private handleRemove = file => {
    const { url } = file
    if (this.props.ossDelete) {
      const key = getOssFileKey(url)
      ossHttp.deleteMulti([key])
    }
    let fileList = this.state.fileList
    fileList = fileList.filter(fileItem => fileItem.uid !== file.uid)
    this.setState({ fileList: fileList }, () => {
      if (this.updateFiles) {
        this.updateFiles(fileList)
      } else {
        this.props.form && this.props.form.setFieldsValue({ quotaApplyDetailFileRespVoList: fileList })
      }
    })
    return true
  }

  private handlePreview = file => {
    const { url } = file
    const fileName = url ? url.substr(url.lastIndexOf('.') + 1).toLowerCase() : ''
    if (fileName.includes('jpg') || fileName.includes('png')) {
      this.setState({ previewVisible: true, previewImage: file.url })
    }
  }

  render() {
    return (
      <div className={classNames('ud-uploader-wrapper', { 'is-empty': !this.state.fileList.length })}>
        <Upload
          accept={this.accept}
          beforeUpload={this.handleUpload}
          fileList={this.state.fileList}
          onPreview={this.handlePreview}
          onRemove={this.handleRemove}
          disabled={this.state.uploadLoading}
        >
          {this.state.fileList.length >= 5 ? null : (
            <Button icon="upload" loading={this.state.uploadLoading}>
              {this.state.uploadText}
            </Button>
          )}
        </Upload>
        <Modal
          visible={this.state.previewVisible}
          footer={null}
          onCancel={() => {
            this.setState({ previewVisible: false })
          }}
        >
          <img alt="图片附件" style={{ width: '100%' }} src={this.state.previewImage} />
        </Modal>
        <span className="ud-uploader-extra">{this.props.extra}</span>
      </div>
    )
  }
}
